import { NavigateService } from './../../../service/navigate.service';
import { GrowlMessageType, MessageBoxService } from './../../../component/messageBoxService';
import { MdSnackBar } from '@angular/material';
import { ObjectCopier } from './../../../common/objectCopier';
import { MdDialogRef, MdDialog, MdDialogConfig } from "@angular/material";
import { Inventory, Modifier } from './../../../model/clerkDataContext';
import { Component, OnInit } from '@angular/core';

export class OrderComboDetailService {
    static Current = new OrderComboDetailService();
    dialogRef: MdDialogRef<OrderComboDetail>;
    orderCombo: OrderComboDetail;
    config: MdDialogConfig = {
        disableClose: false,
        width: '100%',
        position: {
            bottom: '0'
        }
    }
    //注册dialog
    regist(orderCombo: OrderComboDetail) {
        this.orderCombo = orderCombo;
    }
    //打开dialog
    open(dialog: MdDialog, inventory: Inventory, commonMods?: Modifier[], selectOption?) {
        this.dialogRef = dialog.open(OrderComboDetail, this.config);
        this.orderCombo.inventory = <any>ObjectCopier.Copy(inventory);
        let commonModsCopy: any = ObjectCopier.Copy(commonMods);
        commonModsCopy = commonModsCopy.filter((com) => {
            if (!com.applyCategories || !com.applyCategories.length) {
                return true;
            } else {
                let result = com.applyCategories.find((cat) => {
                    let flag = false;
                    for (let cate of inventory.categories) {
                        if (cat.id == cate.id) {
                            flag = true;
                            break;
                        }
                    }
                    return flag;
                });
                if (result) {
                    return true;
                }
                return false;
            }
        });
        this.orderCombo.modifiers = this.sortMods(inventory, commonModsCopy);
        this.recheckMods(this.orderCombo.modifiers, selectOption);
        return new Promise((resolve, reject) => {
            this.dialogRef.afterClosed().subscribe(invt => {
                this.dialogRef = null;
                resolve(invt);
            });
        });
    }

    /**
     * 商品选项必选项排在前面
     */
    private sortMods(invt: Inventory, commonMods: Modifier[]) {
        let mods = [];
        let invtMods = (invt.modifiers && invt.modifiers.length) ? invt.modifiers : [];
        let commMods = (commonMods && commonMods.length) ? commonMods : [];
        mods = invtMods.concat(commMods);
        mods.sort((a, b) => {
            let numA = a.isRequired ? 1 : 0;
            let numB = b.isRequired ? 1 : 0;
            return numB - numA;
        })
        return mods;
    }

    private recheckMods(mods, selectOption) {
        if (!selectOption || !selectOption.modifiers) {
            for (let mod of mods) {
                for (let opt of mod.options) {
                    if (opt.checked) {
                        opt.selected = true;
                    }
                }
            }
            return;
        }
        for (let mod of mods) {
            let item = selectOption.modifiers.items.find(i => {
                return mod.id == i.id
            });
            if (item) {
                for (let opt of item.options) {
                    let optTarget = mod.options.find(o => {
                        return o.id == opt.id;
                    });
                    if (optTarget) {
                        optTarget.selected = true;
                    }
                }
            }
        }
        this.orderCombo.remark = selectOption.description;
    }
}

@Component({
    //moduleId: module.id,
    selector: 'div[order-combo-detail]',
    template: `
        <md-dialog-content>
            <div class="combo-detail-container" fxLayout="column">
                <div tabindex="0" autofocus fxLayout="row" fxLayoutAlign="center center" class="combo-detail-info noshrink">
                    <span fxFlex="100%" class="combo-detail-name">{{inventory.name}}</span>
                    <div id="dialog-close-btn" class="i-close combo-detail-close noshrink" (click)="close()"></div>
                </div>
                <div fxFlex="100%" fxLayout="column" class="v-scroll">
                    <div class="combo-detail-mod">
                        <div class="padding-s" *ngFor="let mod of modifiers">
                            <div class="combo-detail-modname" fxLayout="row" fxLayoutAlign="start center">
                                <span class="color-lightgray">{{mod.name}}</span>
                                <span class="color-primary" *ngIf="mod.isRequired">*</span>
                            </div>
                            <div fxLayout="row" fxLayoutAlign="center center">
                                <div class="combo-detail-option" fxFlex="100%" fxLayout="row" fxLayoutWrap="wrap">
                                    <div class="combo-opt-info" (click)="selectMod(mod, opt)" [ngClass]="{'combo-detail-flexfull':mod.isRequired ,'combo-detail-flex':!mod.isRequired, 'combo-margin':(mod.isRequired&&index>0)||(!mod.isRequired&&index>1),'combo-select':opt.selected}" *ngFor="let opt of mod.options;let index = index">
                                        <span class="noshrink">{{opt.name}}</span>
                                        <span *ngIf="opt.price">（{{opt.price | currencySymbol}}）</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="padding-s noshrink" fxLayout="row" fxLayoutAlign="center center">
                        <textarea (focus)="remarkAreaFocus()" (blur)="remarkAreaBlur()" class="combo-detail-remark" placeholder="请输入备注信息" [(ngModel)]="remark"></textarea>
                    </div>
                </div>
                <button class="combo-detail-btn pct100 bgcolor-accent noshrink normal-btn text-m" fxFlexAlign="end" md-button (click)="confirm()">确定</button>
            </div>
        </md-dialog-content>
    `,
    styleUrls: ['../order.component.scss']
})
export class OrderComboDetail implements OnInit {
    constructor(
        public dialogRef: MdDialogRef<OrderComboDetail>,
        public snackBar: MdSnackBar,
        private msgSvr: MessageBoxService,
        private navSvr: NavigateService
    ) {
        OrderComboDetailService.Current.regist(this);
    }
    inventory: Inventory;
    remark: string;
    modifiers: Modifier[];
    remarkfocus: boolean = false;
    snackBarRef = null;

    ngOnInit() {
        this.navSvr.registGoBack(() => {
            let closeBtn = document.getElementById("dialog-close-btn");
            if (closeBtn) {
                closeBtn.click();
            }
        });
    }
    /**
     * 选择一个商品选项
     */
    selectMod(mod: Modifier, opt) {
        if (opt.selected) {
            delete opt.selected;
            return;
        }
        if (mod.singleton) {
            //单选
            mod.options.forEach(ii => delete ii.selected);
        }
        opt.selected = !opt.selected;
    }

    /**
     * 备注输入框获得焦点
     */
    remarkAreaFocus() {
        console.log("focus")
    }

    /**
     * 备注输入框失去焦点
     */
    remarkAreaBlur() {
        console.log("blur")
    }

    /**
     * 获得选中的商品选项
     */
    private getSelectedMods(mlist: Modifier[]) {
        let result: Modifier[] = [];
        mlist.forEach(x => {
            let opts: any[] = [];
            x.options.forEach(n => { if (n.selected) opts.push(n); });
            if (opts && opts.length > 0) {
                let m = ObjectCopier.Copy<Modifier>(x);
                m.options = opts;
                result.push(m);
            }
        });

        return result;
    }

    /**
     * 校验选择的商品选项是否正确,返回未选中的必选商品选项
     */
    private checkMod(selectMod: Modifier[]) {
        let mustMod = null
        for (let mod of this.modifiers) {
            if (mod.isRequired) {
                let selected = selectMod.find(x => { return x.id == mod.id });
                if (!selected) {
                    mustMod = mod;
                }
            }
        }
        return mustMod;
    }

    buildSelectionOption(selectedMods) {
        let result = <any>{};
        result.modifiers = <any>{};
        result.description = this.remark ? this.remark : "";
        let items = [];
        for (let mod of selectedMods) {
            let item = this.buildItem(mod);
            items.push(item);
        }
        result.modifiers.items = items;
        result.modifiers.amount = this.calcAllAmount(items);
        return result;
    }

    /**
     * 计算商品选项的价格
     * @param {any} options  选中的商品选项
     * @returns
     */
    buildItem(item) {
        let amount = 0;
        let opts = [];
        let itemObj = <any>{};
        if (item && Array.isArray(item.options) && item.options.length) {
            for (let opt of item.options) {
                let optObj: any = ObjectCopier.Copy(opt);
                delete optObj.selected;
                if (opt.price) {
                    amount += opt.price;
                }
                opts.push(optObj);
            }
        }
        itemObj.amount = amount;
        itemObj.id = item.id;
        itemObj.name = item.name;
        itemObj.options = opts;
        return itemObj;
    }

    /**
     * 计算商品选项总价格
     */
    calcAllAmount(items) {
        let amount = 0;
        if (Array.isArray(items) && items.length) {
            for (let item of items) {
                if (item.amount) {
                    amount += item.amount;
                }
            }
        }
        return amount;
    }

    /**
     *关闭dialog，不做修改 
     */
    close() {
        this.dialogRef.close();
    }

    /**
     * 确定选择
     */
    confirm() {
        let selectedMods = this.getSelectedMods(this.modifiers);
        let mustMod = this.checkMod(selectedMods);
        if (mustMod) {
            if (!this.snackBarRef) {
                this.snackBarRef = this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, "【" + mustMod.name + "】为必选项");
                this.snackBarRef.afterDismissed().subscribe(() => {
                    this.snackBarRef = null;
                });
            }
            return;
        }
        let result = this.buildSelectionOption(selectedMods);
        this.dialogRef.close(result);

    }
}